import { computed, defineComponent, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import CellInput from '@/components/CellInput'
import { Address } from '@/types/model'
import { createAddressApi, getAddressApi, updateAddressApi } from '@/api/address'
import { createToast } from '@/components/Toast'
import router from '@/router'

const useEditStautsEffect = (addressId: string) => {
  const isEdit = computed(() => {
    return addressId !== '0'
  })

  return {
    isEdit
  }
}

interface AddressData {
  addressForm: Partial<Address>
}

const useAddressFormEffect = (addressId: string) => {
  const data: AddressData = reactive({
    addressForm: {}
  })

  const getAddress = async () => {
    const res = await getAddressApi(addressId)
    if (res.code === 0) {
      data.addressForm = res.data
    }
  }

  if (addressId !== '0') {
    getAddress()
  }

  const handleSubmit = async (isEdit: boolean) => {
    const handler = isEdit ? updateAddressApi : createAddressApi
    const res = await handler(data.addressForm)
    if (res.code === 0) {
      createToast(res.message)
      router.push({ name: 'AddressManage' })
    }
  }

  return {
    data,
    handleSubmit
  }
}

export default defineComponent({
  name: 'EditAddress',
  setup () {
    const route = useRoute()
    const router = useRouter()
    const addressId = route.params.id as string
    const { isEdit } = useEditStautsEffect(addressId)
    const { data, handleSubmit } = useAddressFormEffect(addressId)

    /* render 函数 */
    return () => {
      const { addressForm } = data
      return (
        <div class="address__edit">
          <header>
            <div class="iconfont icon-back" onClick={ () => { router.back() } }></div>
            <div class="title">{ isEdit.value ? '编辑' : '新建' }收货地址</div>
            <div class="save" onClick={ () => { handleSubmit(isEdit.value) } }>保存</div>
          </header>
          <div class="input__area">
            <CellInput
              label="所在城市"
              v-model={ addressForm.city }
              placeholder="如北京市"
            />
            <CellInput
              label="小区/大厦/学校"
              v-model={ addressForm.area }
              placeholder="如理工大学国防科技园"
            />
            <CellInput
              label="楼号-门牌号"
              v-model={ addressForm.number }
              placeholder="A号楼B层"
            />
            <CellInput
              label="收货人"
              v-model={ addressForm.name }
              placeholder="请填写收货人的姓名"
            />
            <CellInput
              label="联系电话"
              v-model={ addressForm.phone }
              placeholder="请填写收货手机号"
            />
          </div>
        </div>
      )
    }
  }
})
